package com.renwei.yunlong.activity.me;


import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.renwei.yunlong.R;
import com.renwei.yunlong.YunLongApplication;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.InformationBean;
import com.renwei.yunlong.bean.UpdateUserIconBean;
import com.renwei.yunlong.event.MinePageRefreshEvent;
import com.renwei.yunlong.global.EventKey;
import com.renwei.yunlong.global.IntentKey;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.DateTimeUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.utils.UploadManger;
import com.renwei.yunlong.view.RatingBar;
import com.zyf.fwms.commonlibrary.utils.SharedPreUtil;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import github.opensource.dialog.prompt.PromptButton;
import github.opensource.dialog.prompt.PromptButtonListener;
import github.opensource.dialog.prompt.PromptDialog;

import static com.renwei.yunlong.R.id.iv_office_phone;
import static com.renwei.yunlong.R.id.rl_certificate;

/**
 * 人员信息页面
 * <p>
 * Created by Administrator on 2017/8/23.
 */

public class InformationActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener, TakePhoto.TakeResultListener, InvokeListener, TimePickerView.OnTimeSelectListener {
    private static final String TAG = InformationActivity.class.getName();

    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.rl_sex)
    RelativeLayout rlSex;
    @Bind(R.id.rl_born)
    RelativeLayout rlBorn;
    @Bind(R.id.rl_department)
    RelativeLayout rlDepartment;
    @Bind(R.id.rl_grouping)
    RelativeLayout rlGrouping;
    @Bind(R.id.rl_job_number)
    RelativeLayout rlJobNumber;
    @Bind(R.id.rl_character)
    RelativeLayout rlCharacter;
    @Bind(R.id.rl_status)
    RelativeLayout rlStatus;
    @Bind(R.id.rl_phone)
    RelativeLayout rlPhone;
    @Bind(iv_office_phone)
    ImageView ivOfficePhone;
    @Bind(R.id.rl_office_phone)
    RelativeLayout rlOfficePhone;
    @Bind(R.id.rl_email)
    RelativeLayout rlEmail;
    @Bind(R.id.rl_special)
    RelativeLayout rlExpertise;
    @Bind(rl_certificate)
    RelativeLayout rlCertificate;
    @Bind(R.id.tv_nickname)
    TextView tvNickname;
    @Bind(R.id.tv_sex)
    TextView tv_sex;
    @Bind(R.id.tv_birthday)
    TextView tvBirthday;
    @Bind(R.id.tv_department_name)
    TextView tvDepartmentName;
    @Bind(R.id.tv_userGroup_name)
    TextView tvUserGroupName;
    @Bind(R.id.tv_employee_code)
    TextView tvEmployeeCode;
    @Bind(R.id.tv_role_name)
    TextView tvRoleName;
    @Bind(R.id.tv_state)
    TextView tvState;
    @Bind(R.id.tv_mobile_Phone)
    TextView tvMobilePhone;
    @Bind(R.id.tv_office_telephone)
    TextView tvOfficeTelephone;
    @Bind(R.id.tv_email)
    TextView tvEmail;
    @Bind(R.id.tv_special_name)
    TextView tvSpecialName;
    @Bind(R.id.tv_work_number)
    TextView tvWorkNumber;
    @Bind(R.id.iv_head)
    ImageView ivHead;
    @Bind(R.id.rl_click_replace)
    RelativeLayout rlClickReplace;
    @Bind(R.id.rtb_star_fives)
    RatingBar rtBar;
    @Bind(R.id.tv_star_count)
    TextView tvCount;
    @Bind(R.id.tv_certificate_name)
    TextView tvCertificate;

    private PromptDialog promptDialog;
    private TimePickerView pvTime;
    private Uri imageUri;
    //服务商信息
    InformationBean serviceInfoBean;
    //业主个人信息
    InformationBean ownerInfoBean;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_information);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        EventBus.getDefault().register(this);
        initView();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    private void initView() {
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        tvTitle.setText("人员信息");
        ivBack.setOnClickListener(this);
        rlSex.setOnClickListener(this);
        rlBorn.setOnClickListener(this);
        rlPhone.setOnClickListener(this);
        rlExpertise.setOnClickListener(this);
        rlCertificate.setOnClickListener(this);
        rlOfficePhone.setOnClickListener(this);
        rlEmail.setOnClickListener(this);
        rlClickReplace.setOnClickListener(this);
        promptDialog = new PromptDialog(this);
        rtBar.setFocusable(false);
        rtBar.setClickable(false);
        reqUserInfo();
    }


    private void reqUserInfo() {//请求用户信息
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        HashMap map = new HashMap();
        if ("1".equals(companyType)) {
            if (ownerBean.getRows() != null) {
                map.put("employeeId", ownerBean.getRows().getEmployeeId());
                manager.QueryInfomationByEmployeeId(this, "1", JsonMapUtil.mapToJson(map), this);
                Log.e("业主 个人信息jsonBean", JsonMapUtil.mapToJson(map));
            }
        } else if ("2".equals(companyType)) {
            if (serviceLoginBean.getRows() != null) {
                map.put("employeeId", serviceLoginBean.getRows().getEmployeeId());
                manager.QueryInfomationByEmployeeId(this, "2", JsonMapUtil.mapToJson(map), this);
                Log.e("服务商 个人信息jsonBean", JsonMapUtil.mapToJson(map));
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_click_replace:
                PromptButton cancle = new PromptButton("取消", null);
                File file = new File(getApplication().getCacheDir(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                imageUri = Uri.fromFile(file);
                LogUtil.e("onClick: ", imageUri.toString());
                //默认两个按钮为Alert对话框，大于三个按钮的为底部SHeet形式展现
                promptDialog.showAlertSheet("", true, cancle,
                        new PromptButton("打开相册", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                takePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions());
                            }
                        }), new PromptButton("拍照", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
                            }
                        }));
                break;
            case R.id.rl_sex://性别
                selectSex();
                break;
            case R.id.rl_born://生日
                selectTime();
                break;
            case R.id.rl_office_phone:
                Intent phoneIntent = new Intent(this, OfficePhoneActivity.class);
                phoneIntent.putExtra(IntentKey.OFFICE_PHONE, tvOfficeTelephone.getText().toString());
                startActivityForResult(phoneIntent, IntentKey.OFFICE_PHONE_KEY);
                break;
            case R.id.rl_email:
                Intent emailIntent = new Intent(this, EditEmailActivity.class);
                emailIntent.putExtra(IntentKey.OFFICE_EMAIL, tvEmail.getText().toString());
                startActivityForResult(emailIntent, IntentKey.OFFICE_EMAIL_KEY);
                break;
            case R.id.rl_special:
                String ids;
                if ("1".equals(companyType)) {
                    ids = ownerInfoBean.getRows().getTechnicalQualif() == null ? "" : ownerInfoBean.getRows().getTechnicalQualif();
                } else {
                    ids = serviceInfoBean.getRows().getTechnicalQualif() == null ? "" : serviceInfoBean.getRows().getTechnicalQualif();
                }
                startActivity(new Intent(this, SpecialInfoActivity.class).putExtra("ids", ids));
                break;
            case rl_certificate:
                startActivity(new Intent(this, UserCertificateActivity.class).putExtra("from", "else"));
                break;

            default:
                break;

        }
    }


    //选择性别
    private void selectSex() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this); //定义一个AlertDialog
        String[] strarr = {"女", "男"};
        builder.setItems(strarr, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                String sex = "1";
                // 自动生成的方法存根
                if (arg1 == 0) {//女
                    sex = "0";
                } else {//男
                    sex = "1";
                }
                HashMap newmap = new HashMap();
                if ("1".equals(companyType)) {
                    //业主修改性别
                    newmap.put("userId", ownerInfoBean.getRows().getUserId());
                    newmap.put("employeeId", ownerInfoBean.getRows().getEmployeeId());
                    newmap.put("gender", sex);
                } else {
                    //服务商修改性别
                    newmap.put("userId", serviceLoginBean.getRows().getUserId());
                    newmap.put("employeeId", serviceLoginBean.getRows().getEmployeeId());
                    newmap.put("gender", sex);
                }
                ServiceRequestManager manager = ServiceRequestManager.getManager();
                manager.updateUserInfo(InformationActivity.this, JsonMapUtil.mapToJson(newmap), InformationActivity.this);
            }
        });
        builder.show();
    }

    //region  //日期选择相关
    //日期选择
    private void selectTime() {
        pvTime = new TimePickerView.Builder(this, this)
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("", "", "", "", "", "")
                .isCenterLabel(false)
                .setTitleText("出生日期")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(getResources().getColor(R.color.text_dark_black_color)) //设置选中项文字颜色
                .setTextColorOut(getResources().getColor(R.color.color_666666))
                .setDividerColor(getResources().getColor(R.color.color_999999))
                .setCancelText("取消")
                .setCancelColor(getResources().getColor(R.color.color_999999))
                .setSubmitText("确定")
                .setSubmitColor(getResources().getColor(R.color.blue_color))
                .setContentSize(20)
                .setTitleSize(17)
                .build();
        pvTime.show();
    }

    //endregion

    //region net work
    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 3:
                LogUtil.e("业主返回个人信息", result);
                ownerInfoBean = new Gson().fromJson(result, InformationBean.class);
                if (ownerInfoBean.getMessage().getCode() == 200) {//加载成功
                    if (!TextUtils.isEmpty(ownerInfoBean.getRows().getAvatar())) {
                        Glide.with(this)
                                .load(Api.$().OWNER_FILE_URL + ownerInfoBean.getRows().getAvatar())
                                .error(R.mipmap.icon_header_default)
                                .into(ivHead);
                        SharedPreUtil.saveString(this, "owner_avatar", StringUtils.value(Api.$().OWNER_FILE_URL + ownerInfoBean.getRows().getAvatar()));
                    }
                    tvNickname.setText(StringUtils.value(ownerInfoBean.getRows().getName()));
                    tvWorkNumber.setText(StringUtils.value("已解决工单  " + ownerInfoBean.getRows().getWorkOrderNumber()));
                    if ("0".equals(StringUtils.value(ownerInfoBean.getRows().getGender()))) {
                        tv_sex.setText("女");
                    } else if ("1".equals(StringUtils.value(ownerInfoBean.getRows().getGender()))) {
                        tv_sex.setText("男");
                    }
                    String birth = ownerInfoBean.getRows().getBirthday() == null ? "" : ownerInfoBean.getRows().getBirthday();
                    if (birth.contains("T")) {
                        String[] tempDate = birth.split("T");
                        tvBirthday.setText(tempDate[0]);
                    } else {
                        tvBirthday.setText(birth);
                    }
                    tvDepartmentName.setText(StringUtils.value(ownerInfoBean.getRows().getDepartmentName()));
                    tvUserGroupName.setText(StringUtils.value(ownerInfoBean.getRows().getUserGroupName()));
                    tvEmployeeCode.setText(StringUtils.value(ownerInfoBean.getRows().getEmployeeCode()));
                    tvRoleName.setText(StringUtils.value(ownerInfoBean.getRows().getRoleName()));
                    if ("1".equals(StringUtils.value(ownerInfoBean.getRows().getState()))) {
                        if ("1".equals(ownerInfoBean.getRows().getEngineerStatus())) {
                            tvState.setText("正常");
                        } else if ("2".equals(ownerInfoBean.getRows().getEngineerStatus())) {
                            tvState.setText("挂起");
                        }
                    } else if ("2".equals(StringUtils.value(ownerInfoBean.getRows().getState()))) {
                        tvState.setText("删除");
                    }
                    tvMobilePhone.setText(StringUtils.value(ownerInfoBean.getRows().getMobilePhone()));
                    tvOfficeTelephone.setText(StringUtils.value(ownerInfoBean.getRows().getOfficeTelephone()));
                    tvEmail.setText(StringUtils.value(ownerInfoBean.getRows().getEmail()));
                    tvSpecialName.setText(StringUtils.value(ownerInfoBean.getRows().getTechnicalQualifName()));
                    String lock = StringUtils.value(ownerInfoBean.getRows().getLock()).length() == 0 ? "0" : StringUtils.value(ownerInfoBean.getRows().getLock());
                    rtBar.setStar(Float.parseFloat(lock));
                    tvCount.setText(lock);
                    LogUtil.e("个人信息接口信息" + result);
                }
                break;
            case 4:
                LogUtil.e("服务商返回个人信息", result);
                serviceInfoBean = new Gson().fromJson(result, InformationBean.class);
                if (serviceInfoBean.getMessage().getCode() == 200) {
                    if (!TextUtils.isEmpty(serviceInfoBean.getRows().getAvatar())) {
                        Glide.with(this)
                                .load(Api.$().SERVICE_FILE_URL + serviceInfoBean.getRows().getAvatar())
                                .error(R.mipmap.icon_header_default)
                                .into(ivHead);
                        SharedPreUtil.saveString(this, "service_avatar", StringUtils.value(Api.$().SERVICE_FILE_URL + serviceInfoBean.getRows().getAvatar()));
                    }
                    tvNickname.setText(StringUtils.value(serviceInfoBean.getRows().getName()));
                    tvWorkNumber.setText(StringUtils.value("已解决工单" + serviceInfoBean.getRows().getWorkOrderNumber()));
                    if ("0".equals(StringUtils.value(serviceInfoBean.getRows().getGender()))) {
                        tv_sex.setText("女");
                    } else if ("1".equals(StringUtils.value(serviceInfoBean.getRows().getGender()))) {
                        tv_sex.setText("男");
                    }
                    String birth = serviceInfoBean.getRows().getBirthday() == null ? "" : serviceInfoBean.getRows().getBirthday();
                    if (birth.contains("T")) {
                        String[] tempDate = birth.split("T");
                        tvBirthday.setText(tempDate[0]);
                    } else {
                        tvBirthday.setText(birth);
                    }
                    tvDepartmentName.setText(StringUtils.value(serviceInfoBean.getRows().getDepartmentName()));
                    tvUserGroupName.setText(StringUtils.value(serviceInfoBean.getRows().getUserGroupName()));
                    tvEmployeeCode.setText(StringUtils.value(serviceInfoBean.getRows().getEmployeeCode()));
                    tvRoleName.setText(StringUtils.value(serviceInfoBean.getRows().getRoleName()));
                    if ("1".equals(StringUtils.value(serviceInfoBean.getRows().getState()))) {
                        if ("1".equals(serviceInfoBean.getRows().getEngineerStatus())) {
                            tvState.setText("正常");
                        } else if ("2".equals(serviceInfoBean.getRows().getEngineerStatus())) {
                            tvState.setText("挂起");
                        }
                    } else if ("2".equals(StringUtils.value(serviceInfoBean.getRows().getState()))) {
                        tvState.setText("删除");
                    }
                    tvMobilePhone.setText(StringUtils.value(serviceInfoBean.getRows().getMobilePhone()));
                    tvOfficeTelephone.setText(StringUtils.value(serviceInfoBean.getRows().getOfficeTelephone()));
                    tvEmail.setText(StringUtils.value(serviceInfoBean.getRows().getEmail()));
                    tvSpecialName.setText(StringUtils.value(serviceInfoBean.getRows().getTechnicalQualifName()));
                    String lock = StringUtils.value(serviceInfoBean.getRows().getLock()).length() == 0 ? "0" : StringUtils.value(serviceInfoBean.getRows().getLock());
                    rtBar.setStar(Float.parseFloat(lock));
                    tvCount.setText(lock);
                    LogUtil.e("个人信息接口信息" + result);
                }
                break;
            case 999:
                //图片上传成共之后
                LogUtil.e("文件上传成功了" + result);
                //===========================
                Glide.with(this).loadFromMediaStore(imageUri).into(ivHead);
                //===========================
                Gson gson = new Gson();
                UpdateUserIconBean mBean = gson.fromJson(result, UpdateUserIconBean.class);
                //当stutus=1代表文件上传成功
                if ("1".equals(mBean.getStatus())) {
                    HashMap<String, String> newmap = new HashMap();
                    //判断是服务商还是业主用户
                    // 存入内存
                    if ("1".equals(companyType)) {
                        newmap.put("userId", ownerInfoBean.getRows().getUserId());
                        newmap.put("avatar", mBean.getPath());
                        newmap.put("employeeId", ownerInfoBean.getRows().getEmployeeId());
                        ownerBean.getRows().setAvatar(mBean.getPath());
                        mCache.put("loginBean", ownerBean);
                    } else {
                        newmap.put("userId", serviceInfoBean.getRows().getUserId());
                        newmap.put("avatar", mBean.getPath());
                        newmap.put("employeeId", serviceInfoBean.getRows().getEmployeeId());
                        serviceLoginBean.getRows().setAvatar(mBean.getPath());
                        mCache.put("serviceLoginBean", serviceLoginBean);
                    }
                    ServiceRequestManager manager = ServiceRequestManager.getManager();
                    manager.updateUserInfo(this, JsonMapUtil.mapToJson(newmap), this);
                } else {
                    showCenterInfoMsg("");
                }
                break;
            case 888:
                //这里个人资料更新成功之后 发送Eventbus消息更新用户信息
                LogUtil.e("mJson--998" + result);
                EventBus.getDefault().post(new MinePageRefreshEvent(EventKey.UPDATE_USER_INFO));
                reqUserInfo();
                break;
            default:
                LogUtil.e("mJson--default" + result);
                break;
        }
    }
    //endregion


    @Override
    public void onException(int requestId, String code) {
        LogUtil.e("失败的消息---" + requestId + "错误码:" + code);
    }


    @Nullable
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        if (requestCode != 0 && data != null) {
            switch (requestCode) {
                case IntentKey.OFFICE_PHONE_KEY:
                    //接收到手机号码之后更新手机号码
                    String phone = data.getStringExtra(IntentKey.OFFICE_PHONE);
                    if (phone.length() > 0) {
                        HashMap newmap = new HashMap();
                        if ("1".equals(companyType)) {
                            //业主修改性别
                            newmap.put("userId", ownerInfoBean.getRows().getUserId());
                            newmap.put("employeeId", ownerInfoBean.getRows().getEmployeeId());
                            newmap.put("officeTelephone", phone);
                        } else {
                            //服务商修改性别
                            newmap.put("userId", serviceLoginBean.getRows().getUserId());
                            newmap.put("employeeId", serviceLoginBean.getRows().getEmployeeId());
                            newmap.put("officeTelephone", phone);
                        }
                        ServiceRequestManager manager = ServiceRequestManager.getManager();
                        manager.updateUserInfo(InformationActivity.this, JsonMapUtil.mapToJson(newmap), InformationActivity.this);
                    }
                    break;
                case IntentKey.OFFICE_EMAIL_KEY:
                    //接收到手机号码之后更新手机号码
                    String email = data.getStringExtra(IntentKey.OFFICE_EMAIL);
                    if (email.length() > 0) {
                        HashMap newmap = new HashMap();
                        if ("1".equals(companyType)) {
                            //业主修改性别
                            newmap.put("userId", ownerInfoBean.getRows().getUserId());
                            newmap.put("employeeId", ownerInfoBean.getRows().getEmployeeId());
                            newmap.put("email", email);
                        } else {
                            //服务商修改性别
                            newmap.put("userId", serviceLoginBean.getRows().getUserId());
                            newmap.put("employeeId", serviceLoginBean.getRows().getEmployeeId());
                            newmap.put("email", email);
                        }
                        ServiceRequestManager manager = ServiceRequestManager.getManager();
                        manager.updateUserInfo(InformationActivity.this, JsonMapUtil.mapToJson(newmap), InformationActivity.this);
                    }
                    break;
                default:
                    break;

            }

        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    //配置图像压缩相关
    private void configCompress(TakePhoto takePhoto) {
        CompressConfig config;
        LubanOptions option = new LubanOptions.Builder()
                .setMaxSize(1024000)
                .create();
        config = CompressConfig.ofLuban(option);
        config.enableReserveRaw(true);
        takePhoto.onEnableCompress(config, false);
    }

    /**
     * 配置图片裁剪相关参数
     *
     * @return 压缩详情
     */
    private CropOptions getCropOptions() {
        int height = 800;
        int width = 800;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
        builder.setWithOwnCrop(true);
        return builder.create();
    }


    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(InformationActivity.this, InformationActivity.this));
        }
        configCompress(takePhoto);
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        //牌照成功之后上传图片图片上传成功后 回掉onSuccess
        Log.w(TAG, "takeSuccess：" + result.getImage().getOriginalPath());
        Log.w(TAG, "URI：" + imageUri);
        File newFile = null;
        try {
            newFile = new File(new URI(StringUtils.value(imageUri + "")));
            if (newFile.exists()) {
                upLoadFile(newFile);
            } else {
                LogUtil.e("文件不存在");
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
            showCenterInfoMsg(this.getString(R.string.tip_file_is_not_exist));
        }
    }


    public void upLoadFile(File newFile) {
        //上传文件到owner
        if ("1".equals(YunLongApplication.getCompanyType())) {
            UploadManger manger = UploadManger.getManager();
            manger.uploadIcon(InformationActivity.this, newFile, this, ownerBean.getRows().getCompany().getVersionCode()
                    , ownerBean.getRows().getCompany().getCompanyCode());
        } else {//上传文件到serv
            UploadManger manger = UploadManger.getManager();
            manger.uploadIcon(InformationActivity.this, newFile, this, serviceLoginBean.getRows().getCompany().getVersionCode()
                    , serviceLoginBean.getRows().getCompany().getCompanyCode());
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i(TAG, "takephoto------takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i(TAG, getResources().getString(R.string.msg_operation_canceled));
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEventMessage(MinePageRefreshEvent event) {
        switch (event.getMessage()) {
            case EventKey.UPDATE_USER_SPECIAL:
                reqUserInfo();
                break;
            default:
                break;
        }
    }


    @Override
    public void onTimeSelect(Date date, View v) {
        LogUtil.e(TAG, "当前选择时间：" + DateTimeUtils.date2String(date, "yyyy-MM-dd"));
        HashMap newmap = new HashMap();
        if ("1".equals(companyType)) {
            //业主修改出生日期
            newmap.put("userId", ownerInfoBean.getRows().getUserId());
            newmap.put("employeeId", ownerInfoBean.getRows().getEmployeeId());
            newmap.put("feteDay", DateTimeUtils.date2String(date, "yyyy-MM-dd"));
        } else {
            //服务商修改出生日期
            newmap.put("userId", serviceLoginBean.getRows().getUserId());
            newmap.put("employeeId", serviceLoginBean.getRows().getEmployeeId());
            newmap.put("feteDay", DateTimeUtils.date2String(date, "yyyy-MM-dd"));
        }
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        manager.updateUserInfo(InformationActivity.this, JsonMapUtil.mapToJson(newmap), InformationActivity.this);
        LogUtil.e("mJson" + JsonMapUtil.mapToJson(newmap));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
